package com.jdew.thkj.activity;

import android.app.Dialog;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.onitemInterface.SearchClickListener;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.utils.WeiboDialogUtils;
import com.jdew.thkj.view.PopupWindowView;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by cangku on 2017/9/7.
 */

public class FindPwActivity extends BaseActivity {
    @Bind(R.id.tel)
    EditText tel;
    @Bind(R.id.yzcode)
    EditText yzcode;
    @Bind(R.id.tvcode)
    TextView tvcode;
    @Bind(R.id.mima)
    EditText mima;
    @Bind(R.id.mima_sure)
    EditText mimaSure;
    @Bind(R.id.find_pw)
    Button findPw;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    @Bind(R.id.num)
    TextView num;
    @Bind(R.id.quhao)
    LinearLayout quhao;
    private String telcode;
    private SharedPreferences sp;
    SharedPreferences.Editor editor;
    private Dialog mWeiboDialog;
    private PopupWindowView popupWindowView;
    private int typeId = 1;
    private String telphone;

    @Override
    public int bindLayout() {
        return R.layout.activity_forgort_pw;
    }

    @Override
    public void initView(View view) {
        sp = getSharedPreferences("user", MODE_PRIVATE);
        editor = sp.edit();
        telcode = sp.getString("code", "");
        back.setVisibility(View.VISIBLE);
        popupWindowView = new PopupWindowView(this);
        popupWindowView.setOnItemClickListener(new SearchClickListener() {
            @Override
            public void onItemClick(String position) {
                num.setText("+" + position);
                popupWindowView.dismiss();
            }
        });
        title.setText("找回密码");
        back.setOnClickListener(this);
        tvcode.setOnClickListener(this);
        findPw.setOnClickListener(this);
        quhao.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
            case R.id.right: {
                finish();
            }
            break;
            case R.id.find_pw: {
                toFindPs();
            }
            break;
            case R.id.tvcode: {
                getCode();
            }
            break;
            case R.id.quhao: {
                popupWindowView.showAsDropDown(quhao);
            }
            break;
            default:
                break;
        }

    }

    public void toFindPs() {
        if (TextUtils.isEmpty(tel.getText())) {
            ToastUtils.getInstance(this).showMessage("请输入手机号码");
        } else if (TextUtils.isEmpty(mima.getText()) || TextUtils.isEmpty(mimaSure.getText())) {
            ToastUtils.getInstance(this).showMessage("请输入新密码");
        } else if (!mima.getText().toString().equals(mimaSure.getText().toString())) {
            ToastUtils.getInstance(this).showMessage("两次密码不一致");
        } else if (TextUtils.isEmpty(yzcode.getText())) {
            ToastUtils.getInstance(this).showMessage("请填写验证码");
        } else if (mima.getText().length() < 6 || mima.getText().length() > 16) {
            ToastUtils.getInstance(this).showMessage("密码长度需要在6-16位之间");
        } else if (null == telcode || !yzcode.getText().toString().equals(telcode)) {
            ToastUtils.getInstance(this).showMessage("验证码错误");
        } else {
            if (!num.getText().toString().equals("+86")) {
                telphone = num.getText().toString().replace("+", "") + tel.getText().toString().trim();
            } else {
                telphone = tel.getText().toString().trim();
            }
            mWeiboDialog = WeiboDialogUtils.createLoadingDialog(this);
            String timesamp = RegexValidateUtils.getTime13();
            String numsamp = RegexValidateUtils.getRandom10();
            HashMap<String, Object> map = new HashMap();
            map.put("UserPhone", telphone);
            map.put("UserPwd", mima.getText().toString());
            RetrofitManager.getInstance(AppConfig.BASE_URL)
                    .createReq(RequestApi.class).SetLoginPwd(map, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "UserPhone" + telphone + "UserPwd" + mima.getText().toString())).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
                @Override
                public void onCompleted() {
                    WeiboDialogUtils.closeDialog(mWeiboDialog);
                }

                @Override
                public void onError(Throwable e) {
                    WeiboDialogUtils.closeDialog(mWeiboDialog);
                }

                @Override
                public void onNext(JSONObject jsonObject) {
                    WeiboDialogUtils.closeDialog(mWeiboDialog);
                    if (jsonObject.getString("code").equals("0")) {
                        ToastUtils.getInstance(FindPwActivity.this).showMessage("找回密码成功，即将返回");
                        finish();
                    } else if (jsonObject.getString("code").equals("-2")) {
                        ToastUtils.getInstance(FindPwActivity.this).showMessage("此账号还未注册");
                    }
                }
            });
        }
    }

    public void getCode() {
        if (TextUtils.isEmpty(tel.getText())) {
            ToastUtils.getInstance(FindPwActivity.this).showMessage("请输入手机号码");
            return;
        } else if (num.getText().toString().trim().equals("+86") && !RegexValidateUtils.checkCellphone(tel.getText().toString())) {
            ToastUtils.getInstance(FindPwActivity.this).showMessage("请输入正确的手机号码");
            return;
        }
        if (num.getText().toString().trim().equals("+86")) {
            typeId = 1;
            telphone = tel.getText().toString().trim();
        } else {
            typeId = 2;
            telphone = num.getText().toString().replace("+", "") + tel.getText().toString().trim();
        }
        timer.start();
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).GetCode(telphone, typeId, RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "phone" + telphone + "typeId" + typeId)).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
                ToastUtils.getInstance(FindPwActivity.this).showMessage("发送异常");
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.get("code").equals("0")) {
                    ToastUtils.getInstance(FindPwActivity.this).showMessage(json.getString("message"));
                    telcode = json.getString("data");
                    editor.putString("code", telcode);
                    editor.apply();
                } else if (json.get("code").equals("-1")) {
                    ToastUtils.getInstance(FindPwActivity.this).showMessage(json.getString("message"));
                }
            }
        });
    }

    /**
     * 取消倒计时
     *
     * @param v
     */
    public void oncancel(View v) {
        timer.cancel();
    }

    /**
     * 开始倒计时
     *
     * @param v
     */
    public void restart(View v) {
        timer.start();
    }

    private CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tvcode.setEnabled(false);
            tvcode.setTextColor(Color.GRAY);
            tvcode.setText((millisUntilFinished / 1000) + "秒后可重发");
        }

        @Override
        public void onFinish() {
            tvcode.setEnabled(true);
            tvcode.setTextColor(getResources().getColor(R.color.theme_color));
            tvcode.setText("发送验证码");
            timer.cancel();
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != popupWindowView) {
            popupWindowView.dismiss();
        }
        if (timer != null) {
            timer.cancel();
        }
    }
}
